#include "swlog.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>


#define LOG_BUFFER_SIZE 256

static LogLevel_t current_log_level = LOG_LEVEL_INFO;
static char log_buffer[LOG_BUFFER_SIZE];
static log_output_fn_t log_output = log_default_output;

// 默认输出函数实现
void log_default_output(const char *str, size_t len)
{
    HAL_UART_Transmit(&LOG_UART_HANDLE, (uint8_t *)str, len, HAL_MAX_DELAY);
}

void log_set_output(log_output_fn_t output_fn)
{
    log_output = output_fn;
}

void log_init(void)
{
    current_log_level = LOG_LEVEL_NONE;  
}

void log_set_level(LogLevel_t level)
{
    current_log_level = level;
}

void log_error(const char *format, ...)
{
    if(current_log_level >= LOG_LEVEL_ERROR) {
        va_list args;
        va_start(args, format);
        int len = snprintf(log_buffer, LOG_BUFFER_SIZE, "[ERROR] ");
        len += vsnprintf(log_buffer + len, LOG_BUFFER_SIZE - len, format, args);
        len += snprintf(log_buffer + len, LOG_BUFFER_SIZE - len, "\r\n");
        va_end(args);
        
        log_output(log_buffer, strlen(log_buffer));
    }
}

void log_warning(const char *format, ...)
{
    if(current_log_level >= LOG_LEVEL_WARNING) {
        va_list args;
        va_start(args, format);
        int len = snprintf(log_buffer, LOG_BUFFER_SIZE, "[WARNING] ");
        len += vsnprintf(log_buffer + len, LOG_BUFFER_SIZE - len, format, args);
        len += snprintf(log_buffer + len, LOG_BUFFER_SIZE - len, "\r\n");
        va_end(args);
        
        log_output(log_buffer, strlen(log_buffer));
    }
}

void log_info(const char *format, ...)
{
    if(current_log_level >= LOG_LEVEL_INFO) {
        va_list args;
        va_start(args, format);
        int len = snprintf(log_buffer, LOG_BUFFER_SIZE, "[INFO] ");
        len += vsnprintf(log_buffer + len, LOG_BUFFER_SIZE - len, format, args);
        len += snprintf(log_buffer + len, LOG_BUFFER_SIZE - len, "\r\n");
        va_end(args);
        
        log_output(log_buffer, strlen(log_buffer));
    }
}
